﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    public class EditDrag : MonoBehaviour, IPointerDownHandler
    {
        public bool xEnable = true;
        public bool yEnable = true;
        public bool canChangeColor = true;
        public bool isAlphaBtn;
        public Transform[] excludes;

        bool canDrag = false;
        Vector2 previousPos;
        RectTransform trans { get { return transform as RectTransform; } }
        List<MaskableGraphic> graphics = new List<MaskableGraphic>();
        Color[] graphicColors;
        Vector2 oldPos;
        bool isOnlyText;
        Canvas _canvas;
        Canvas canvas { get { return _canvas ?? (_canvas = GetComponentInParent<Canvas>()); } }

        string SaveKey
        {
            get
            {
                string str = gameObject.name.Replace("(Clone)", "");
                if (transform.parent) str += "_" + transform.parent.name;
                return str;
            }
        }

        void OnDestroy()
        {
            MainController.onEditModeEnable -= OnEditModeEnable;
        }

        void Awake()
        {
            if (isAlphaBtn)
            {
                MaskableGraphic[] imgs = GetComponentsInChildren<MaskableGraphic>();
                for (int i = 0; i < imgs.Length; i++)
                {
                    imgs[i].color = new Color(0, 0, 0, 0); ;
                }
            }
            MainController.onEditModeEnable += OnEditModeEnable;
            oldPos = trans.anchoredPosition;
        }

        void Start()
        {
            string key = SaveKey;
            float storageX = DataStorage.GetFloat(key + "_X", -98765);
            if (storageX != -98765)
            {
                Vector2 pos = trans.anchoredPosition;
                if (xEnable)
                {
                    pos.x = DataStorage.GetFloat(key + "_X");
                }
                if (yEnable)
                {
                    pos.y = DataStorage.GetFloat(key + "_Y");
                }
                trans.anchoredPosition = pos;
            }
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            canDrag = true;
            previousPos = BUtils.ScreenToUGUIPoint(Input.mousePosition, canvas);
        }

        void Update()
        {
            if (MainController.isEditMode && canDrag)
            {
                Vector2 pos = BUtils.ScreenToUGUIPoint(Input.mousePosition, canvas);
                Vector2 delta = pos - previousPos;
                previousPos = pos;
                Vector2 _pos = trans.anchoredPosition;
                if (xEnable)
                {
                    _pos.x += delta.x;
                }
                if (yEnable)
                {
                    _pos.y += delta.y;
                }
                trans.anchoredPosition = _pos;
            }
            if (Input.GetMouseButtonUp(0))
            {
                canDrag = false;
            }
        }

        void OnEditModeEnable(bool b, bool save)
        {
            if (b)
            {
                oldPos = trans.anchoredPosition;
                canDrag = false;
            }
            //变色
            if (canChangeColor)
            {
                if (b)
                {
                    FindAllGraphic();
                }
                for (int i = 0; i < graphics.Count; i++)
                {
                    graphics[i].color = b ? new Color(0.5f, 1f, 0.5f, graphicColors[i].a) : graphicColors[i];
                }
            }

            //取消控制
            BButton button = GetComponent<BButton>();
            if (button)
            {
                button.enabled = !b;
            }
            StateButton stateButton = GetComponent<StateButton>();
            if (stateButton)
            {
                stateButton.enabled = !b;
            }
            Dropdown dropdown = GetComponent<Dropdown>();
            if (dropdown)
            {
                dropdown.enabled = !b;
            }

            if (!b)
            {
                if (save)
                {
                    string key = SaveKey;
                    if (xEnable)
                    {
                        DataStorage.SetFloat(key + "_X", trans.anchoredPosition.x);
                    }
                    if (yEnable)
                    {
                        DataStorage.SetFloat(key + "_Y", trans.anchoredPosition.y);
                    }
                }
                else
                {
                    trans.anchoredPosition = oldPos;
                }
            }
        }

        bool IsExclude(Transform trans)
        {
            for (int i = 0; i < excludes.Length; i++)
            {
                if (excludes[i] == trans) return true;
            }
            return false;
        }

        void FindAllGraphic()
        {
            //RawImage经常被卸载重新创建，所以这里需要每次都查找
            graphics.Clear();
            isOnlyText = true;
            FindGraphic(transform);
            //如果不是只有Text，就把Text排除掉
            if (!isOnlyText)
            {
                for (int i = 0; i < graphics.Count; i++)
                {
                    if (graphics[i] is Text)
                    {
                        graphics.RemoveAt(i);
                    }
                }
            }
            graphicColors = new Color[graphics.Count];
            for (int i = 0; i < graphics.Count; i++)
            {
                graphicColors[i] = graphics[i].color;
            }
        }

        void FindGraphic(Transform trans)
        {
            MaskableGraphic graphic = trans.GetComponent<MaskableGraphic>();
            if (graphic && !IsExclude(graphic.transform))
            {
                if (graphic is RawImage)
                {
                    isOnlyText = false;
                }
                graphics.Add(graphic);
                for (int i = 0; i < trans.childCount; i++)
                {
                    FindGraphic(trans.GetChild(i));
                }
            }
        }
    }
}